#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker() {
    std::unique_lock<std::mutex> lock(mtx);
    std::cout << "Worker thread is waiting." << std::endl;
    cv.wait(lock, []{ return ready; });  // 使用谓词，持续检查条件
    std::cout << "Worker thread is notified." << std::endl;
    // 执行后续工作
    for (int i = 0; i < 5; ++i) {
        std::cout << "Worker is processing data " << i << std::endl;
    }
    std::cout << "Worker finished processing." << std::endl;
}

int main() {
    std::thread t(worker);

    std::this_thread::sleep_for(std::chrono::seconds(2)); // 延迟以模拟主线程处理其他任务
    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;  // 设置 ready 为 true
        std::cout << "Main thread sets ready and notify worker." << std::endl;
    }
    cv.notify_all();  // 唤醒所有等待的线程

    t.join();
    std::cout << "Main thread and worker thread have completed." << std::endl;

    return 0;
}